<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 2020/12/12
 * Time: 19:20
 */

namespace app\api\controller;


use app\admin\controller\User;
use app\common\model\UserModel;
use app\common\module\Wechat;
use think\Db;
use think\Validate;

class Recycler extends Common
{
    //提交审核
    public function submitApply(){
        $userInfo = $this->checkSign();
        $res = Validate::make()
            ->rule([
                'true_name|姓名'=>"require|max:10",
                'id_card|身份号'=>"require|idCard|max:20",
                'phone|电话'=>'require|mobile|max:12',
                'regionid|区域'=>'require|number|max:11',
                'positive|身份证正面'=>'require|max:180',
                'back|身份证反面'=>'require|max:180',
                'remarks|描述'=>"max:200"
            ]);
        if (!$res->check($userInfo)) {
            return  package(10006,$res->getError());
        }
        $this->preventSubmit($userInfo['user_id']);
        $regionInfo = Db::name('region')->where('id',$userInfo['regionid'])->field('open,name')->find();
        if(!$regionInfo){
            return  package(10008,'区域未找到！');
        }
        if($regionInfo['open'] ==0){
            return  package(10008,'当前区域未开通！');
        }
        $data = [
            'user_id'=>$userInfo['user_id'],
            'true_name'=>$userInfo['true_name'],
            'nickname'=>$userInfo['nickname'],
            'headimgurl'=>$userInfo['headimgurl'],
            'id_card'=>$userInfo['id_card'],
            'phone'=>$userInfo['phone'],
            'region_id'=>$userInfo['regionid'],
            'region_name'=>$regionInfo['name'],
            'remarks'=>$userInfo['remarks']??'',
            'create_time'=>date("Y-m-d H:i:s"),
            'status'=>0,
            'openid'=>$userInfo['openid'],
            'longitude'=>$userInfo['longitude']??'',
            'latitude'=>$userInfo['latitude']??'',
            'back'=>$userInfo['back'],
            'positive'=>$userInfo['positive'],
        ];
        if(isset($userInfo['id']) && $userInfo['id']){
            $info = Db::name('recycler_apply')->where('id',$userInfo['id'])->update($data);
        }else{
            $info = Db::name('recycler_apply')->insert($data);
        }

        return checkRes($info,'提交成功，请耐心等待审核!',false);
    }
    //判断是否有过审核
    public function checkIsApply(){
        $userInfo = $this->checkSign();
        $info = Db::name('recycler_apply')
            ->where('user_id',$userInfo['user_id'])
            ->field('id,status,reason,true_name,id_card,remarks,phone,region_id,positive,back')
            ->find();
        if($info && $info['status'] ==1){
            $token = $userInfo['token']??'';
            $userInfos =  redisHashGet('auth',$token);
            $userInfos['user_class'] = 2;
            $userInfos['region_id'] = $info['region_id'];
            redisHashSet('auth',$token,$userInfos);
            redisHashSet('auth',$userInfos['openid'],$userInfos);
        }
        return package(0,'操作成功',$info);
    }
    //获取回收员订单
    public function getRecyclerOrder(){
        $userData = $this->checkSign();
        $status = $userData['status']??0;
        if($userData['user_class'] !=2){
            $class = Db::name('users')->where('id',$userData['user_id'])->value('user_class');
            //取出来更新
            $token = $userData['token']??'';
            $userInfos = redisHashGet('auth',$token);
            $userInfos['user_class'] = $class;
            redisHashSet('auth',$token,$userInfos);
            redisHashSet('auth',$userInfos['openid'],$userInfos);
            if($class !=2){
                return package(10006,'当前用户不是回收员');
            }

        }
        $page  = intval($userData['page']??1);
        $where = [
            ['is_delete','=',0],
            ['region_id','=',$userData['region_id']]

        ];
//        $whereor = [];
        if($status ==0){
            $where[] = ['order_status','=',0];
        }elseif ($status ==3){
//            $where[] = ['order_status','=',0];
            $where[] = ['accept_user_id','=',$userData['user_id']];
            $where[] =['order_status','in','0,1,2'];
        }else{
            $where[] = ['accept_user_id','=',$userData['user_id']];
            $where[] = ['order_status','=',$status];
        }
        $list = Db::name('orders')
            ->where($where)
//            ->whereOr($whereor)
            ->field('id,order_number,total_money,address_type,total_integral,type_name,true_name,phone,address_name,floor_address,remarks,weight_type,create_time,appointment_date,appointment_time,order_status as status,all_type')
            ->page($page,20)
            ->order('id','desc')
            ->select();
        //储存用户查订单时间
        redisHashSet('selectOrderTime',$userData['user_id'],date("Y-m-d H:i:s"));
        return package(0,'获取成功',$list);
    }
    //获取订单信息
    public function getRecyclerOrderInfo(){
        $userData = $this->checkSign();
        $id = intval($userData['id']??0);
        $where = [
            ['is_delete','=',0],
            ['id','=',$id],
            ['region_id','=',$userData['region_id']],
        ];
        $info = Db::name('orders')
            ->where($where)->find();
        if($info['order_status'] ==2){
            $info['details'] =Db::name('order_detail')->where('order_id',$info['id'])->field('small_type_name,price,number,unit')->select();
        }
        return package(0,'获取成功',$info);
    }

    //接单
    public function acceptOrder(){
        $userData = $this->checkSign();
        if($userData['user_class'] !=2){
            return package(10006,'当前用户不是回收员');
        }
        $id = intval($userData['id']??0);
        if(!$id){
            return package(10004,'id错误');
        }
        $where = [
            ['is_delete','=',0],
            ['id','=',$id],
            ['region_id','=',$userData['region_id']]
        ];
        $info = Db::name('orders')->lock(true)->where($where)->field('order_status,order_number,type_name')->find();
        if(!$info){
            return package(10004,'订单未找到');
        }
        if($info['order_status'] ==6){
            return package(10004,'订单已取消');
        }
        if($info['order_status'] !=0){
            return package(10004,'订单已经被抢了');
        }
        $applyinfo  = Db::name('recycler_apply')->where('user_id',$userData['user_id'])->field('true_name,phone')->find();
        if(!$applyinfo){
            return package(10004,'用户回收信息错误');
        }
        Db::startTrans();
        $result = Db::name('orders')->where('id',$id)->update([
            'accept_user_id'=>$userData['user_id'],
            'accept_user_name'=>$applyinfo['true_name'],
            'accept_user_phone'=>$applyinfo['phone'],
            'order_status'=>1,
            'accept_time'=>date("Y-m-d H:i:s")
        ]);
        if($result){
            Db::commit();
            //推送订单信息
            $wechat = new Wechat();
            $wechat->sendOrderMsg($userData['openid'],$info['order_number'],$info['type_name'].' 上门回收',$applyinfo['true_name'],$applyinfo['phone']);
            return package(0,'接单成功');
        }else{
            Db::rollback();
            return package(10024,'接单失败');
        }
    }
    //获取回收小类的价格
    public function getRecyclerPrice(){
        $userData = $this->checkSign();
        if($userData['user_class'] !=2){
            return package(10006,'当前用户不是回收员');
        }
        $id = intval($userData['id']??0);

        if(!$id){
            return package(1004,'id错误');
        }
        $info = Db::name('orders')->where([
            ['id','=',$id],
            ['accept_user_id','=',$userData['user_id']],
            ['order_status','=',1]
        ])->field('region_id,type_id')->find();
        if(!$info){
            return package(1005,'订单信息未找到错误');
        }
        $integral_proportion =  Db::name('config')
            ->where('id',1)
            ->cache(true)
            ->value('integral_proportion');
        $list =Db::name('recycling_list')->field('id,type_id,name,describe,unit,reference_price')
            ->select();
        $in = '';
        foreach ($list as $v){
            $in.=$v['id'].',';
        }
        $prices = Db::name('recycling_reg_price')
            ->where('region_id',$info['region_id'])
            ->whereIn('list_id',$in)
            ->field('price,list_id')
            ->select();
        foreach ($prices as $v){
            foreach ($list as $key =>$val){
                $list[$key]['is_show'] = false;
                if($val['id'] ==$v['list_id']){
                    $list[$key]['price'] = $v['price'];
                }
            }
        }
        return package(0,'获取成功',['list'=>$list,'integral_proportion'=>$integral_proportion,'type_id'=>$info['type_id']]);
    }
    //结算
    public function settlement(){
        $data = $this->checkSign(true);
        $post = $data['data']??array();
        if($data['user_class'] !=2){
            return package(10006,'当前用户不是回收员');
        }
        if(!$post){
            return package(6,'请选择至少选择一个回收品类！');
        }
        $in = '';
        foreach ($post as $v){
            if(isset($v['price']) && is_float($v['price'])){
                return package(6,'价格填写错误！');
            }
            $in.=$v['type_id'].',';
        }
        $order_id = intval($data['order_id']??0);
        $where = [
            ['is_delete','=',0],
            ['id','=',$order_id],
            ['accept_user_id','=',$data['user_id']]
        ];
        $this->preventSubmit($data["user_id"]);
        $info = Db::name('orders')->where($where)->lock(true)->field('id,order_number,user_id,order_status,region_id')->find();
        if(!$info){
            return package(1006,'订单信息未找到！');
        }
        if($info['order_status'] !=1){
            return package(1006,'订单重复结算！');
        }

        $namelist = Db::name('recycling_list')->wherein('id',$in)->field('id as small_id,name,unit')->select();
        $pricelist = Db::name('recycling_reg_price')
            ->cache(true)
            ->where('region_id',$info['region_id'])
            ->wherein('list_id',$in)
            ->field('price,list_id')->select();
        $insert_data = [];
        $total_price = 0;
        $total_integral = 0;
        $integral_proportion =  Db::name('config')
            ->where('id',1)
            ->cache(true)
            ->value('integral_proportion');
        $time = date("Y-m-d H:i:s");
        foreach ($post as $v1){
            foreach ($namelist as $v2){
                foreach ($pricelist as $v3){
                    if($v1['type_id'] == $v2['small_id'] && $v2['small_id']==$v3['list_id']){
                        $money = ($v3['price']*100)*$v1['number'];
                        $insert_data[] = [
                            'order_id'=>$info['id'],
                            'order_number'=>$info['order_number'],
                            'user_id'=>$info['user_id'],
                            'accept_user_id'=>$data['user_id'],
                            'small_type_id'=>$v2['small_id'],
                            'small_type_name'=>$v2['name'],
                            'price'=>$v3['price'],
                            'number'=>$v1['number'],
                            'unit'=>$v2['unit'],
                            'integral'=>strpos($v2['name'], '铜')?0:($money/$integral_proportion)/100,
                            'create_time'=>$time
                        ];
                        $total_price+=$money/100;
                        $total_integral +=strpos($v2['name'], '铜')?0:($money/$integral_proportion)/100;
                    }
                }

            }
        }
        Db::startTrans();
        $result1 = Db::name('orders')->where($where)->update([
            'order_status'=>2,
            'success_time'=>$time,
            'total_money'=>$total_price,
            'total_integral'=>intval($total_integral)
        ]);
        $result2 = Db::name('order_detail')->insertAll($insert_data);
        if($result1 && $result2){
            Db::commit();
            return package(0,'结算成功');
        }else{
            Db::rollback();
            return package(10006,'结算失败');
        }
    }


    public function upLocation(){
        $userData = $this->checkSign();
        if($userData['user_class'] !=2){
            return package(10006,'当前用户不是回收员');
        }
        $longitude = $userData['longitude']??'';
        $latitude = $userData['latitude']??'';
        $res = UserModel::where('id',$userData['user_id'])->update([
            'longitude'=>$longitude,
            'latitude'=>$latitude,
            'location_time'=>date("Y-m-d H:i:s")
        ]); //更新时间
        $lastTime = redisHashGet('selectOrderTime',$userData['user_id']);//获取最后查询时间
        $where = [
            ['is_delete','=',0],
            ['region_id','=',$userData['region_id']],
            ['order_status','=',0]
        ];
        if($lastTime){
            $where[] = ['create_time','>',$lastTime];
        }
        $isnot_order = Db::name('orders')
            ->where($where)
            ->value('id');
        return package(0,'上传成功',$isnot_order?true:false);

    }


}